<template>
  <div class="app-container">
    <div class="body-container mt0">
      <el-row :gutter="20">
        <!--单位数据-->
        <el-col :span="4" :xs="24">
          <div class="head-container">
            <el-input v-model="deptName" placeholder="请输入单位名称" clearable size="small" prefix-icon="el-icon-search" style="margin-bottom: 20px" />
          </div>
          <div class="head-container">
            <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false" :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current @node-click="handleNodeClick" />
          </div>
        </el-col>
        <!--用户数据-->
        <el-col :span="20" :xs="24">
          <div class="search-container">
            <div class="search-title">
              查询条件
            </div>
            <div class="search-form">
              <div class="form-row">
                <div class="form-column">
                  <span class="column-title">姓名</span>
                  <el-input v-model="queryParams.personnelName" placeholder="请输入" class="input-w150" clearable @keyup.enter.native="handleQuery" />
                </div>
                <div class="form-column">
                  <span class="column-title">单位</span>
                  <treeselect class="input-w150" v-model="queryParams.unitCode" :options="deptTreeList" :show-count="true" placeholder="请选择" />
                </div>
                <div class="form-column">
                  <span class="column-title">警衔</span>
                  <el-select v-model="queryParams.policeRankCode" placeholder="请选择" clearable filterable class="input180">
                    <el-option v-for="dict in dict.type.sys_police_rank_code" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
                </div>
                <div class="form-column">
                  <span class="column-title">军籍状态</span>
                  <el-select v-model="queryParams.militaryStatus" placeholder="请选择" clearable filterable class="input180">
                    <el-option v-for="dict in dict.type.sys_military_status" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
                </div>
                <div class="form-column">
                  <span class="column-title">在位状态</span>
                  <el-select v-model="queryParams.workingStatus" placeholder="请选择" clearable filterable class="input180">
                    <el-option v-for="dict in dict.type.sys_user_staff_status" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
                </div>
                <div class="form-column">
                  <span class="column-title">专业</span>
                  <el-select v-model="queryParams.majorCode" placeholder="请选择" clearable filterable class="input180">
                    <el-option v-for="dict in dict.type.sys_user_major_code" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
                </div>
                <div class="form-column">
                  <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
                  <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
                </div>
              </div>
            </div>
          </div>

          <div class="body-container">
            <div class="operation-bar">
              <div class="bar-title">
                学员列表
              </div>
              <div class="bar-btn__wrapper">
                <div class="bar-btn" @click="handleDels"><i class="el-icon-delete"></i>批量删除</div>
                <div class="bar-btn" @click="handleAdd"><i class="el-icon-plus"></i>新增</div>
                <div class="bar-btn" @click="handleImport"><i class="el-icon-upload2"></i>导入</div>
                <div class="bar-btn" @click="handleDownLoad"><i class="el-icon-download"></i>导出</div>
              </div>
            </div>

            <el-table v-loading="loading" :data="userList" stipe @selection-change="handleSelectionChange1">
              <el-table-column type="selection" width="55">
              </el-table-column>
              <el-table-column label="编号" align="center" key="userId" prop="personnelUnitNum" />
              <el-table-column label="姓名" align="center" key="userName" prop="personnelName" width="150">
                <div slot-scope="scope" style="display: flex;display: -webkit-flex;align-items: center;justify-content: flex-start;">
                  <div style="width: 60px; text-align: center;">
                    <el-tag type="danger" v-if="selectDictLabel(dict.type.sys_user_staff_status, scope.row.workingStatus) == '休假'">{{
                      selectDictLabel(dict.type.sys_user_staff_status, scope.row.workingStatus) }}</el-tag>
                    <el-tag type="success" v-else-if="selectDictLabel(dict.type.sys_user_staff_status, scope.row.workingStatus) == '在位'">{{
                      selectDictLabel(dict.type.sys_user_staff_status, scope.row.workingStatus) }}</el-tag>
                    <el-tag type="warning" v-else-if="selectDictLabel(dict.type.sys_user_staff_status, scope.row.workingStatus) == '培训'">{{
                      selectDictLabel(dict.type.sys_user_staff_status, scope.row.workingStatus) }}</el-tag>
                  </div> {{ scope.row.personnelName }}
                </div>
              </el-table-column>
              <el-table-column label="警衔" prop="policeRankCode" align="center">
                <template slot-scope="scope">
                  {{ selectDictLabel(dict.type.sys_police_rank_code, scope.row.policeRankCode,) }}
                </template>
              </el-table-column>
              <el-table-column label="职务" prop="positionCode" align="center">
                <template slot-scope="scope">
                  {{ selectDictLabel(dict.type.sys_position_code, scope.row.positionCode,) }}
                </template>
              </el-table-column>
              <el-table-column label="专业" prop="majorCode" align="center">
                <template slot-scope="scope">
                  {{ selectDictLabel(dict.type.sys_user_major_code, scope.row.majorCode,) }}
                </template>
              </el-table-column>
              <el-table-column label="入伍时间" align="center" width="150" prop="enlistmentTime">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.enlistmentTime, '{y}-{m}-{d}') }}</span>

                </template>
              </el-table-column>
              <el-table-column label="入伍年限" align="center">
                <template slot-scope="scope">
                  <div v-if="scope.row.enlistmentTime">
                    {{ countYearFun(parseTime(scope.row.enlistmentTime, '{y}-{m}-{d}')) > 0 ?
                    countYearFun(parseTime(scope.row.enlistmentTime, '{y}-{m}-{d}')) + '年' : '-' }}
                    <span class="manColor" v-if="dict.type.sys_exit_year[0].value <= countYearFun(parseTime(scope.row.enlistmentTime, '{y}-{m}-{d}'))">满</span>
                  </div>
                  <div v-else>
                    -
                  </div>

                </template>
              </el-table-column>
              <el-table-column label="军籍状态" align="center">
                <template slot-scope="scope">
                  {{ selectDictLabel(dict.type.sys_military_status, scope.row.militaryStatus,) }}
                </template>
              </el-table-column>
              <!-- <el-table-column label="人才库" align="militaryStatus">
                <template slot-scope="scope">
                  <el-tag type="success" v-if="scope.row.talentStatus == 1">是</el-tag>
                  <el-tag type="info" v-if="scope.row.talentStatus == 2">否</el-tag>
                </template>
              </el-table-column> -->
              <el-table-column label="审核状态" align="center">
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.approvalStatus == 1">待审核</el-tag>
                  <el-tag type="success" v-if="scope.row.approvalStatus == 2">通过</el-tag>
                  <el-tag type="danger" v-if="scope.row.approvalStatus == 3">不通过</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" min-width="270" fixed="right" class-name="small-padding fixed-width">
                <div class="table-option" slot-scope="scope" v-if="scope.row.roleId !== 1">
                  <span @click="handleToDetail(scope.row)">详情</span>
                  <span @click="handleEdit(scope.row)">编辑</span>
                  <span @click="handleAddData(scope.row)" v-if="scope.row.personnelName != 'admin' && scope.row.talentStatus == false">添加到人才库</span>
                  <span class="danger" v-if="scope.row.personnelName != 'admin'" @click="handleDelete(scope.row)">删除</span>
                  <span class="danger" v-if="scope.row.personnelName != 'admin'" @click="handleRestPwd(scope.row)">重置密码</span>
                </div>
              </el-table-column>
            </el-table>
            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 新增或编辑用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="850px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="16">
            <el-row>
              <el-col :span="12">
                <el-form-item label="用户姓名" prop="personnelName">
                  <el-input class="input180" v-model="form.personnelName" placeholder="请输入" maxlength="100" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="性别" prop="gender">
                  <el-select class="input180" v-model="form.gender" placeholder="请选择" clearable filterable>
                    <el-option label="男" :value="1"></el-option>
                    <el-option label="女" :value="2"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="出生日期" prop="dateOfBirth">
                  <el-date-picker type="month" value-format="yyyy-MM" v-model="form.dateOfBirth" class="input180" placeholder="请选择" clearable></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="血型" prop="bloodType">
                  <el-select v-model="form.bloodType" placeholder="请选择" clearable filterable class="input180">
                    <el-option v-for="dict in dict.type.sys_user_blood_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="籍贯" prop="jiguan">
                  <el-cascader v-model="form.jiguan" class="input180" :options="chinaLocations" placeholder="请选择" clearable></el-cascader>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="详细地址" prop="birthplaceAddress">
                  <el-input v-model="form.birthplaceAddress" class="input180" placeholder="请输入" maxlength="90" clearable />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="警衔" prop="policeRankCode">
                  <el-select v-model="form.policeRankCode" placeholder="请选择" clearable filterable class="input180">
                    <el-option v-for="dict in dict.type.sys_police_rank_code" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="职务" prop="positionCode">
                  <el-select v-model="form.positionCode" placeholder="请选择" clearable filterable class="input180">
                    <el-option v-for="dict in dict.type.sys_position_code" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="8">
            <el-form-item label="头像" prop="personnelPic">
              <el-upload :class="{ 'hide': fileList.length == 1, 'upload-demo': true }" ref="uploadImg" :limit="1" list-type="picture-card" :action="fileAction" :headers="fileHeaders" :file-list="fileList" :before-upload="beforeFileUpload" :on-success="handleImageSuccess" :on-remove="handleRemove">
                <i slot="default" class="el-icon-plus"></i>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过10M</div>
              </el-upload>
            </el-form-item>
          </el-col>

          <!-- <el-col :span="8">
            <el-form-item label="军人证件号" prop="personnelUnitNum">
              <el-input v-model="form.personnelUnitNum" class="input180" placeholder="请输入" clearable />
            </el-form-item>
          </el-col> -->
          <el-col :span="8">
            <el-form-item label="身份证号码" prop="idCardNo">
              <el-input v-model="form.idCardNo" class="input180" placeholder="请输入" maxlength="18" clearable />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="在位状态" prop="workingStatus">
              <el-select v-model="form.workingStatus" placeholder="请选择" clearable filterable class="input180">
                <el-option v-for="dict in dict.type.sys_user_staff_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="政治面貌" prop="politicalStatus">
              <el-select class="input180" v-model="form.politicalStatus" placeholder="请选择" clearable filterable>
                <el-option v-for="dict in dict.type.sys_political_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="8">
            <el-form-item label="角色" v-if="actionType == 'edit'" prop="roleIdList">
              <el-select v-model="form.roleIdList" class="input180" placeholder="请选择" clearable filterable>
                <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName"
                  :value="item.roleId"></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->

          <el-col :span="8">
            <el-form-item label="专业" prop="majorCode">
              <el-select v-model="form.majorCode" placeholder="请选择" clearable filterable class="input180">
                <el-option v-for="dict in dict.type.sys_user_major_code" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="军籍状态" prop="militaryStatus">
              <el-select class="input180" v-model="form.militaryStatus" placeholder="请选择" clearable filterable>
                <el-option v-for="dict in dict.type.sys_military_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="入伍时间" prop="enlistmentTime">
              <el-date-picker v-model="form.enlistmentTime" value-format="yyyy-MM" type="month" class="input180" placeholder="请选择" clearable></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="归属单位" prop="unitCode">
              <treeselect class="input180" style="margin-bottom: 0px;" v-model="form.unitCode" :options="deptOptions" :show-count="true" placeholder="请选择" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="毕业院校" prop="graduatedSchool">
              <el-input class="input180" v-model="form.graduatedSchool" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="个人特长" prop="specialties">
              <el-input type="textarea" v-model="form.specialties" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="奖惩情况" prop="rewardsAndPunishments">
              <el-input type="textarea" v-model="form.rewardsAndPunishments" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-tabs>
              <el-tab-pane label="任职经历">
                <el-input type="textarea" :rows="6" v-model="form.mainExperience" placeholder="请输入" clearable />
              </el-tab-pane>
              <el-tab-pane label="培训、学习、重大任务经历">
                <el-input type="textarea" :rows="6" v-model="form.otherMainExperience" placeholder="请输入" clearable />
              </el-tab-pane>
            </el-tabs>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="学员导入" :visible.sync="uploadialog" width="400px" append-to-body>
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="导入单位">
          <treeselect class="input180" style="margin-bottom: 12px;" v-model="importForm.unitCode" :options="deptOptions" :show-count="true" placeholder="请选择" />
        </el-form-item>
      </el-form>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :data="importForm" name="file" :headers="fileHeaders" :action="upload.url" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>

          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="downloadExcel">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="uploadDisable" :loading="uploadDisable" @click="submitFileForm">确
          定</el-button>
        <el-button @click="uploadialog = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 重置密码按钮操作 -->
    <el-dialog title="重置密码" :visible.sync="restPwdDialog" width="30%">
      <el-form ref="resPwdFrom" :model="resPwdFrom" :rules="resPwdRules" label-width="80px">
        <el-form-item label="密码配置" prop="configId">
          <el-select v-model="resPwdFrom.configId" placeholder="请选择" clearable filterable class="input180">
            <el-option v-for="dict in dict.type.sys_normal_pwd" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="restPwdDialog = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmitResetPwd('resPwdFrom')">确 定</el-button>
      </span>
    </el-dialog>

    <UserDetail :id="personnelId" :visible.sync="userDialog"></UserDetail>
  </div>
</template>



<script>
import UserDetail from '@/components/userDetail.vue'
import { roleOptionSelect } from "@/api/role";
import { addUser, delUser, updateUser, getUserProfile, resetUserPwd, exportPersonnelList, delsUser } from '@/api/system/user'
import { deptTree, deptList, excludeDeptList, personnelList, deptAdd, deptUpdate, deptDel } from "@/api/org";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import provinceJson from "../../system/user/province.json";
import { addPersonalTalent } from "@/api/talent";
import { getDeptName } from "@/utils/ruoyi";

export default {

  dicts: ['sys_police_rank_code', 'sys_exit_year', 'sys_military_status', 'sys_political_status', 'sys_normal_pwd', 'sys_user_staff_status', 'sys_position_code', 'sys_user_blood_type', 'sys_user_major_code'],
  components: { Treeselect, UserDetail },
  data () {
    return {
      importForm: {
        unitCode: ''
      },
      uploadDisable: false,
      upload: {
        isUploading: false,
        updateSupport: 0,
        url: process.env.VUE_APP_BASE_API + '/personnel/importPersonnel',
      },
      uploadialog: false,
      resPwdFrom: {},
      restPwdDialog: false,
      actionType: 'add',
      roleList: [],
      userList: [],
      deptName: '',
      fileAction: process.env.VUE_APP_BASE_API + '/common/upload',
      fileHeaders: {
        Authorization: "Bearer " + getToken()
      },
      fileList: [],  //图片
      chinaLocations: provinceJson, //省市区json
      resPwdRules: {
        configId: [
          { required: true, message: "配置不能为空", trigger: "blur" }
        ]
      },
      rules: {
        // personnelName: [
        //   { required: true, message: "用户名称不能为空", trigger: "blur" },
        //   { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        // ],

        // workingStatus: [
        //   { required: true, message: "在位状态不能为空", trigger: "blur" }
        // ],
        // enlistmentTime: [
        //   { required: true, message: "入伍时间不能为空", trigger: "blur" }
        // ],
        // gender: [
        //   { required: true, message: "用户性别不能为空", trigger: "blur" }
        // ],
        // militaryStatus: [
        //   { required: true, message: "军籍状态不能为空", trigger: "blur" }
        // ],
        // politicalStatus: [
        //   { required: true, message: "政治面貌不能为空", trigger: "blur" }
        // ],

        // dateOfBirth: [
        //   { required: true, message: "用户出生日期不能为空", trigger: "blur" }
        // ],
        // unitCode: [
        //   { required: true, message: "用户归属单位不能为空", trigger: "blur" }
        // ],
        // loginName: [
        //   { required: true, message: "登录不能为空", trigger: "blur" }
        // ],
        // password: [
        //   { required: true, message: "登录密码不能为空", trigger: "blur" },
        //   { min: 5, max: 20, message: '登录密码长度必须介于 5 和 20 之间', trigger: 'blur' }
        // ],
      },
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      title: "",
      deptOptions: undefined,
      open: false,
      dateRange: [],
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      multipleSelection: [],
      userDialog: false,
      personnelId: '',
      queryParams: {
        pageNum: 1,
        pageSize: 30,
      },
    };
  },
  computed: {
    downloadUrl () {
      return process.env.VUE_APP_DOWNLOAD_URL
    },
    deptTreeList () {
      return this.$store.state.user.deptTreeList
    },
    deptList () {
      return this.$store.state.user.deptList
    },
  },
  watch: {
    // 根据名称筛选单位树
    deptName (val) {
      this.$refs.tree.filter(val);
    }
  },
  created () {
    this.getList();
    this.getDeptTree();
    this.getRoleList();
  },
  methods: {
    handleSelectionChange1 (val) {
      this.multipleSelection = val;
    },
    handleDels () {
      if (this.multipleSelection.length <= 0) {
        this.$modal.msgWarning('请选勾选要删除的人员');
      } else {
        let ids = this.multipleSelection.map(item => item.id);
        console.log(ids)
        let that = this;
        this.$modal.confirm('是否确认删除?').then(async function (res) {
          if (res == 'confirm') {
            let response = await delsUser(ids.join(','))
            if (response.code == 200) {
              that.$message.success('删除成功')
            } else {
              that.$message.error(response.msg)
            }
          }
        }).then(() => {
          this.getList();
        }).catch(() => { });
      }
    },
    async handleDownLoad () {
      let params = {
        userType: 2,
        ...this.queryParams
      }
      let res = await exportPersonnelList(params);
      let blob = new Blob([res], {
        type: "application/octet-stream"
      });
      let objectUrl = URL.createObjectURL(blob);
      let a = document.createElement("a");
      a.href = objectUrl;
      a.setAttribute("download", "人员信息.xlsx");
      a.click();
      window.URL.revokeObjectURL(blob);
    },
    // 新增到人才库
    async handleAddData (row) {
      let sourceObj = {
        "personnelId": row.id,
      }
      let res = await addPersonalTalent(sourceObj)
      if (res.code === 200) {
        this.$modal.msgSuccess("添加成功");
      } else {
        this.$modal.msgWarning(res.msg);
      }
    },
    // 计算时间差
    countYearFun (val) {
      if (val == '') {
        return ''
      }
      let year = 0;
      var today = new Date();
      var birthDate = new Date(val);
      year = today.getFullYear() - birthDate.getFullYear();
      var monthDiff = today.getMonth() - birthDate.getMonth();
      if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
        year--;
      }
      return year
    },

    handleToDetail (row) {
      this.userDialog = true;
      this.personnelId = String(row.id)
    },
    // 获取权限列表
    async getRoleList () {
      const res = await roleOptionSelect()
      // console.log(res)
      if (res.code === 200) {
        let tmpList = res.data
        this.roleList = tmpList.filter(item => {
          // return item.roleKey !== 'common'
          return item
        })
        // this.roleIdList = res.data
      }
    },
    getDeptName (id) {
      return getDeptName(this.deptList, id)
    },
    // 文件上传前检查
    beforeFileUpload (file) {
      var FileExt = file.name.replace(/.+\./, "");
      const isLtM = file.size / 1024 / 1024 < 150;
      const fileTypeList = ['jpg', 'jpeg', 'png']
      let isFileType = fileTypeList.indexOf(FileExt.toLowerCase()) > -1
      if (!isFileType || !isLtM) {
        this.$message.error('请检查文件格式以及大小');
      }
      return isFileType && isLtM;
    },
    // 文件上传成功
    handleImageSuccess (res, file) {
      if (res.code === 200) {
        this.fileList.push({
          name: file.originalFilename,
          fileName: res.fileName,
          url: this.downloadUrl + res.fileName
        })
      }
    },
    // 文件删除
    handleRemove (file, fileList) {
      this.fileList = [];
      console.log(this.fileList)
      // let index = fileList.indexOf(file);
      // this.fileList.splice(index, 1)
    },

    /** 查询用户列表 */
    getList () {
      this.loading = true;
      let params = {
        userType: 2,
        ...this.queryParams
      }
      personnelList(params).then(response => {
        if (response.code == 200) {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
        } else {
          this.loading = false;
          this.$message.error(response.msg)
        }
      });
    },
    /** 查询单位下拉树结构 */
    getDeptTree () {
      deptTree().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode (value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick (data) {
      this.queryParams.unitCode = data.id;
      // this.queryParams.unitCodeList = data.id;
      this.handleQuery();
    },
    // 用户状态编辑
    handleStatusChange (row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.userName + '"用户吗？').then(function () {
        return changeUserStatus(row.userId, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function () {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      }
      this.dateRange = [];
      this.queryParams.unitCode = undefined;
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 更多操作触发
    handleCommand (command, row) {
      switch (command) {
        case "handleResetPwd":
          this.handleResetPwd(row);
          break;
        case "handleAuthRole":
          this.handleAuthRole(row);
          break;
        default:
          break;
      }
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.open = true;
      this.fileList = [];
      this.actionType = 'add',
        this.title = "新增学员";
    },
    /** 编辑按钮操作 */
    handleEdit (row) {
      this.reset();
      const userId = row.id;
      getUserProfile(userId).then(response => {
        response.data.bloodType = String(response.data.bloodType)
        response.data.workingStatus = String(response.data.workingStatus)
        response.data.politicalStatus = String(response.data.politicalStatus)
        response.data.militaryStatus = String(response.data.militaryStatus)
        this.form = response.data;
        if (response.data.roleIdList) {
          this.form.roleIdList = response.data.roleIdList[0];
        }

        if (response.data.personnelPic) {
          this.fileList = [{
            name: response.data.personnelPic,
            url: this.downloadUrl + response.data.personnelPic
          }]
        }
        if (response.data.provinceCode) {
          this.form.jiguan = [response.data.provinceCode, response.data.cityCode, response.data.areaCode]
        } else {
          this.form.jiguan = []
        }
        this.open = true;
        this.title = "编辑学员";
        this.actionType = 'edit'
      });
    },
    /** 重置密码按钮操作 */
    handleRestPwd (row) {
      let that = this;
      this.$modal.confirm('是否确认重置密码?').then(async function (res) {
        console.log(res)
        if (res == 'confirm') {
          let pwd = that.dict.type.sys_normal_pwd[0].value
          let params = {
            personnelId: row.id,
            password: pwd,
          }
          resetUserPwd(params).then(response => {
            that.$modal.msgSuccess("重置成功");
          });
        }
      }).then(() => {
        that.getList();
      }).catch(() => { });



    },

    /** 分配角色操作 */
    handleAuthRole: function (row) {
      const userId = row.userId;
      this.$router.push("/system/user-auth/role/" + userId);
    },
    /** 提交按钮 */
    submitForm: function () {
      let that = this;
      this.$refs["form"].validate(valid => {
        if (valid) {
          let params = {
            userType: 2,
            ...this.form
          }
          if (this.form.jiguan && this.form.jiguan[0]) {
            params.provinceCode = this.form.jiguan[0];
          }
          if (this.form.jiguan && this.form.jiguan[1]) {
            params.cityCode = this.form.jiguan[1];
          }
          if (this.form.jiguan && this.form.jiguan[2]) {
            params.areaCode = this.form.jiguan[2];
          }
          if (this.fileList.length > 0) {
            params.personnelPic = this.fileList[0].fileName;
          } else {
            params.personnelPic = ''
          }
          if (params.dateOfBirth) {
            params.age = this.countYearFun(params.dateOfBirth);
          }
          if (this.form.roleIdList) {
            params.roleId = this.form.roleIdList;
          }
          delete params.jiguan;
          if (params.id != undefined) {
            delete params.password;
            delete params.loginName;
            delete params.talentStatus;
            updateUser(params).then(response => {
              this.$modal.msgSuccess("编辑成功");
              this.open = false;
              this.getList();
              this.$store.dispatch('GetUserList')
            });
          } else {
            params.roleId = 3;
            addUser(params).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.$store.dispatch('GetUserList')
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      let that = this;
      this.$modal.confirm('是否确认删除?').then(async function (res) {
        if (res == 'confirm') {
          let response = await delUser(row.id)
          if (response.code == 200) {
            that.$message.success('删除成功')
          } else {
            that.$message.error(response.msg)
          }
        }
      }).then(() => {
        this.getList();
      }).catch(() => { });
    },

    /** 导入按钮操作 */
    handleImport () {
      this.uploadialog = true
    },
    /** 下载模板操作 */
    downloadExcel () {
      let a = document.createElement('a')
      a.href = '/static/user_template.xlsx'
      a.download = '导入学员模板.xlsx'
      a.style.display = 'none'
      document.body.appendChild(a)
      a.click()
      a.remove()
    },
    // // 文件上传中处理
    handleFileUploadProgress (event, file, fileList) {
      this.upload.isUploading = true;
    },
    // // 文件上传成功处理
    handleFileSuccess (response, file, fileList) {
      this.uploadialog = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.uploadDisable = false;
      if (response.code == 200) {
        this.$message.success('导入成功！')
      } else {
        this.$message.error(response.msg)
      }
      this.getList();
    },
    // // 提交上传文件
    submitFileForm () {
      this.uploadDisable = true;
      this.$refs.upload.submit()
    }
  }
};
</script>
<style>
.input180 {
  display: block;
  width: 170px !important;
}

.disabled .el-upload.el-upload--picture-card {
  display: none !important;
}

.disabled .el-button--success.is-plain {
  display: none !important;
}

.hide .el-upload--picture-card {
  display: none;
}

.manColor {
  color: red;
}
</style>